import csv

import discord
import asyncio
from flask import Flask, request, jsonify,render_template
import threading
from queue import Queue
import pandas as pd
import os

# ...




from Salai import PassPromptToSelfBot, send_text_message

YOUR_BOT_TOKEN = ''
CHANNEL_ID = ''

intents = discord.Intents.default()
intents.typing = False
intents.presences = False

client = discord.Client(intents=intents)
message_queue = Queue()

def print_message(message):
    msg = f'[{message.created_at}] {message.author}: {message.content}'
    if message.embeds:
        for embed in message.embeds:
            msg += f'\nEmbed title: {embed.title}\nEmbed description: {embed.description}\nEmbed URL: {embed.url}'
    if message.attachments:
        for attachment in message.attachments:
            msg += f'\nAttachment URL: {attachment.url}'
    return msg



def check_file_empty(file_path):
    return os.stat(file_path).st_size == 0

@client.event
async def on_message(message):
    if str(message.channel.id) == CHANNEL_ID:
        msg = print_message(message)
        message_queue.put((message.author.id, msg))
        print('---')
        if message.attachments:
            for attachment in message.attachments:
                await fetch_messages()
        print(msg)
        print(message.attachments)
        print(message)

        if message.attachments:
            for attachment in message.attachments:
                previous_msg = message_queue.get()
                if 'userid:' in previous_msg[1]:
                    new_data = pd.DataFrame({'key': [previous_msg[1]], 'value': [attachment.url.replace('https://cdn.discordapp.com', 'http://154.40.45.28/discord_image')]})
                    if not os.path.isfile('data.csv'):
                        new_data.to_csv('data.csv', index=False, encoding='utf-8')
                    else:
                        if check_file_empty('data.csv'):
                            new_data.to_csv('data.csv', index=False, encoding='utf-8')
                        else:
                            data = pd.read_csv('data.csv', encoding='utf-8')
                            data = pd.concat([data, new_data], ignore_index=True)
                            data.to_csv('data.csv', index=False, encoding='utf-8')

async def fetch_messages():
    await client.wait_until_ready()
    channel = client.get_channel(int(CHANNEL_ID))
    messages = [msg async for msg in channel.history(limit=100)]

    with open('output.csv', 'w', newline='', encoding='utf-8') as csvfile:
        fieldnames = ['User ID', 'URL', 'Timestamp', 'Content']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()

        for i in range(len(messages) - 1, 0, -1):
            message = messages[i]
            if 'userid:' in message.content:
                next_message = messages[i - 1]
                if next_message.attachments:
                    original_url = next_message.attachments[0].url
                    new_url = original_url.replace('https://cdn.discordapp.com', 'http://154.40.45.28/discord_image')
                    #if message.content.split('userid:')[1].strip() 为string则不存储
                    if not message.content.split('userid:')[1].strip().isdigit():
                        continue
                    writer.writerow({
                        'User ID': message.content.split('userid:')[1].strip(),
                        'URL': new_url,
                        'Timestamp': message.created_at.isoformat(),
                        'Content': message.content
                    })

def run_discord_bot():
    client.run(YOUR_BOT_TOKEN)

app = Flask(__name__)

def get_messages_by_user_id(user_id):
    data = pd.read_csv('output.csv')
    filtered_data = data[data['User ID'] == int(user_id)]
    return filtered_data.to_dict('records')

@app.route('/get_messages', methods=['GET'])
def get_messages():
    user_id = request.args.get('userid')
    if user_id is None:
        return "User ID parameter is missing", 400
    messages = get_messages_by_user_id(user_id)
    print(messages)
    print(jsonify(messages))
    return jsonify(messages)


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/send_command', methods=['POST'])
def process_send_command():
    prompt = request.form.get('prompt')
    user_id = request.form.get('userid')

    response = send_text_message(CHANNEL_ID,'userid:'+ user_id)
    print(response)
    print(response.text)

    if response.status_code >= 400:
        print(response.text)
        print(response.status_code)
    else:
        print("Your image is being prepared, please wait a moment...")

    response = PassPromptToSelfBot(prompt)
    print(response)
    print(response.text)

    if response.status_code >= 400:
        print(response.text)
        print(response.status_code)
    else:
        print("Your image is being prepared, please wait a moment...")

    return "Command sent", 200


@client.event
async def on_ready():
    print(f'Bot已登录为{client.user}')


if __name__ == '__main__':
    # 使用另一个线程运行Discord bot
    bot_thread = threading.Thread(target=run_discord_bot)
    bot_thread.start()
    app.run(host='0.0.0.0', port=5002, debug=True)


